using System.Diagnostics.CodeAnalysis;
using System.Reflection.Metadata;
using GameStore.Api.Dtos;
using GameStore.Api.Entities;
using GameStore.Api.Repositoriesa;

namespace GameStore.Api.Endpoints;

public static class GamesEndpoints
{

    const string GetGameEndpointName = "GetGame";
    // public static RouteHandlerBuilder MapGet(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, Delegate handler);
    // public static RouteGroupBuilder MapGroup(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string prefix);

    // 扩展 IEndpointRouteBuilder 接口 
    public static RouteGroupBuilder MapGamesEndpoints(this IEndpointRouteBuilder endpoints)
    {

        var group = endpoints.MapGroup("/games").WithParameterValidation();

        group.MapGet("/", async (IGamesRepository repository) => (await repository.GetAllAsync()).Select(game => game.AsDto()));

        group.MapGet("/{id}", async (IGamesRepository repository,ILogger<Program> logger,int id) =>
        {
            logger.LogInformation("test");
            Game? game =await repository.GetAsync(id);
            if (game is null)
            {
                return Results.NotFound();
            }
            return Results.Ok(game.AsDto());
        }).WithName(GetGameEndpointName);

        group.MapPost("/", (IGamesRepository repository, CreateGameDto gameDto) =>
        {

            Game game = new()
            {
                Name = gameDto.Name,
                Genre = gameDto.Genre,
                Price = gameDto.Price,
                ReleaseDate = gameDto.ReleaseDate,
                ImageUri = gameDto.ImageUri
            };
            repository.CreateAsync(game);

            return Results.CreatedAtRoute(GetGameEndpointName, new { id = game.Id }, game);
        });



        group.MapPut("/{id}", async(IGamesRepository repository, int id, UpdateGameDto updatedGame) =>
        {

            Game? existingGame =await repository.GetAsync(id);
            if (existingGame is null)
            {
                return Results.NotFound();
            }
            existingGame.Name = updatedGame.Name;
            existingGame.Genre = updatedGame.Genre;
            existingGame.Price = updatedGame.Price;
            existingGame.ReleaseDate = updatedGame.ReleaseDate;
            existingGame.ImageUri = updatedGame.ImageUri;

            await repository.UpdateAsync(existingGame);

            return Results.NoContent();
        });

        group.MapDelete("/{id}", async (IGamesRepository repository, int id) =>
        {
            Game? game =await repository.GetAsync(id);
            if (game is not null)
            {
                await repository.DeleteAsync(id);
            }
            return Results.NoContent();
        });


        return group;

    }

}


